#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10005;
int n, m;
struct node {
	int v, w;
};
vector <node> g[N];
queue <int> q;
int num[N], inq[N], d[N];
bool spfa () {
	memset (d, -0x3f, sizeof(d));
	d[0] = 0;
	q.push(0);
	num[0]++;
	inq[0] = 1;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		inq[u] = 0;
		for (unsigned i = 0; i < g[u].size(); i++) {
			int v = g[u][i].v;
			int w = g[u][i].w;
			if (d[v] < d[u] + w) {
				d[v] = d[u] + w;
				if (!inq[v]) {
					q.push(v);
					num[v]++;
					if (num[v] >= n) {
						return false;
					}
				}
			}
		}
	}
	return true;
}
int main() {
	scanf ("%d%d", &n, &m);
	int u, v, a, b;
	bool flag;
	for (int i = 1; i <= m; i++) {
		scanf ("%d%d%d%d", &v, &u, &a, &b);
		flag = 0;
		for (int j = 0; j < g[u].size(); j++) {
			if (v == g[u][j].v) {
				flag = 1;
				g[u][j].w = max (g[u][j].w, a);
			}
		}
		if (!flag) {
			g[u].push_back((node){v, a});
		}
		flag = 0;
		for (int j = 0; j < g[v].size(); j++) {
			if (u == g[v][j].v) {
				flag = 1;
				g[v][j].w = max (g[v][j].w, -b);
			}
		}
		if (!flag) {
			g[v].push_back((node){u, -b});
		}
	}
	bool tmp = spfa();
	int ans = 0;
	if (tmp) {
		for (int i = 0; i < n; i++) {
			ans = max (ans, -d[i]);
		}
		printf ("%d\n", ans);
	} else {
		printf ("-1\n");
	}
	return 0;
}
